package com.hsogoo.study.spring.propertysource;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;

/**
 * Created by za-huangsaigang on 2018/9/17.
 */
public class ConfigPropertySourceProcessor implements EnvironmentAware, BeanFactoryPostProcessor, PriorityOrdered {

    private ConfigurableEnvironment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
        System.out.println("environment set...");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        System.out.println("ConfigPropertySourceProcessor.postProcessBeanFactory() invoked...");
        CompositePropertySource compositePropertySource = new CompositePropertySource("composite");
        Map<String, Object> map = Maps.newHashMap();
        map.put("appName", "configApp");
        MapPropertySource appSource = new MapPropertySource("app", map);
        compositePropertySource.addPropertySource(appSource);
        Map<String, Object> map1= Maps.newHashMap();
        map1.put("envName", "envName");
        MapPropertySource envSource = new MapPropertySource("env", map1);
        compositePropertySource.addPropertySource(envSource);
        environment.getPropertySources().addFirst(compositePropertySource);

    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
